/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import com.sun.org.apache.bcel.internal.util.Class2HTML;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author XMANI
 */
public class LoginDao {

    Connection cn= null;
    public LoginDao() {
        try {
//            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
//            cn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=DBSJ_Thi1","sa","123");

            Class.forName("org.apache.derby.jdbc.ClientDriver");
            cn= DriverManager.getConnection("jdbc:derby://localhost:1527/CSDL_DBSL", "app", "app");

            if (cn !=null) {
                System.out.println("ket noi");
            }

            Statement st = cn.createStatement();
            st.executeUpdate("delete from Login");

            PreparedStatement pst = cn.prepareCall("insert into Login values(?,?) ");
            pst.setString(1, "admin");
            pst.setString(2, hashMD5("admin"));
            pst.executeUpdate();
        } catch (SQLException ex) {
            Logger.getLogger(LoginDao.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(LoginDao.class.getName()).log(Level.SEVERE, null, ex);
        }
    }



    public String hashMD5(String pass) {
        String strTemp = "";

        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] hash = md.digest(pass.getBytes("UTF8"));
            for (int i = 0; i < hash.length; i++) {
                strTemp += Byte.toString(hash[i]);

            }
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(LoginDao.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(LoginDao.class.getName()).log(Level.SEVERE, null, ex);
        }

        return strTemp;

    }
    public boolean comparePass(String user, String pass){
        try {
            PreparedStatement pst = cn.prepareCall("Select Password from Login where UserName=?");
            pst.setString(1, user);
            ResultSet rs = pst.executeQuery();
            rs.next();
            String strPass = rs.getString("Password");
            if (strPass.equalsIgnoreCase(hashMD5(pass))) {
                return true;
            }
        } catch (SQLException ex) {
                return false;
        }

        return false;
    }
}
